Docker Tips
Any edit in a Dockerfile will cause re-builds of consequential steps, so put lines that rarely changes in front1
Avoid using COPY .
to copy a whole folder, only copy files are needed to avoid rebuild when any file changes in the folder1
Too many RUN commands increase layers. Try to combine set steps into one.1
Don't install any development/debug tools/packages for production, only install everything that is needed. like using --no-install-recommends
with apt
1
remove package cache1
use official images when possible: using python3.7 instead of ubuntu when the image is for a python app.1
use more specific tags, which show the version explicitly; also specify the minimal image when possible, install everything manually1
- build from source in a consistent environment (use docker to build)
- fetch & install dependencies in a separate step
- use multi-stage builds to remove build dependencies 1
docker images can be manually moved to another host if both public and private registries aren't able to be used. 2 3
on source
docker save myimage:latest | gzip > myimage_latest.tar.gz
on destination
docker load < myimage_latest.tar.gz
Remove containers. containers can be removed automatically if --rm
is used with docker run
, we can use the follow command to erase them.4
docker container prune
we can stop and erase all containers as well
docker container stop $(docker container ls -aq)
docker container rm $(docker container ls -aq)
Get IP address of a container.5
Modern Docker
docker inspect -f '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}' container_name_or_id
Old Docker
docker inspect --format '{{ .NetworkSettings.IPAddress }}' container_name_or_id
customized function for shell6
Pop this into your ~/.bashrc (Linux) or ~/.bash_profile (Mac)
dockip() {
docker inspect --format '{{ .NetworkSettings.IPAddress }}' "$@" }
Runnig docker as a non-root user7
A general pricipal is: build everything as usual, then switch to a non-root user to run the service.
before entrypoint
USER <username>